package com.common.config;

import com.li.model.User;
import com.li.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.Date;
import java.util.Optional;


@Configuration
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    //2.授权
    //访问被限制的资源时被调用用
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo ();
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        User user = (User)session.getAttribute("USER_SESSION");

        //待修改
        if (user==null){

            //授权
            info.addStringPermission("unLogin");
            return info;
        }
        String perm = userService.getUserPosition(user.getGrade());
        System.out.println("用户权限:"+perm);
        //info.addRole(perm);
        //授权
        info.addStringPermission(perm);
        return info;
        //return null;
    }
    //1.认证 使用subject.login()方法时被调用
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        //连接真实的数据库
        Optional<User> user = userService.queryUserByName(userToken.getUsername());
        //账号认证
        if (!user.isPresent()){
            return null;//null 抛出 UnknowAccountException
        }
        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("USER_SESSION",user.get());
        user.get().setLastLogin(new Date());
        userService.updateUser(user.get());
        //userToken.setRememberMe(true);
        //密码认证
        //密码加密：MD(选择)
        //第一个参数传递user后在doGetAuthorizationInfo方法里面就能拿到
        return new SimpleAuthenticationInfo("",user.get().getPassword(),"");

    }


}
